package com.ebt.m.proposal_v2.helper;

import android.annotation.TargetApi;
import android.net.http.SslError;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.ebt.m.proposal_v2.utils.ViewUtils;

/**
 * WebView配置
 *
 * @author archer.qi
 *         Created on 2017/5/15.
 */
public class WebViewSetter {
    private WebView mWebView;

    /**
     * 设置关联WebView
     *
     * @param webView
     * @return
     */
    public WebViewSetter with(WebView webView) {
        mWebView = webView;
        return this;
    }

    /**
     * 支持JavaScript
     *
     * @return
     */
    public WebViewSetter supportJavaScript() {
        mWebView.getSettings().setJavaScriptEnabled(true);
        return this;
    }

    /**
     * 支持屏幕适应
     *
     * @return
     */
    public WebViewSetter wrapViewPort() {
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        return this;
    }

    /**
     * 支持缩放
     *
     * @return
     */
    public WebViewSetter supportZoom() {
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setSupportZoom(true);
        return this;
    }

    /**
     * 文本编码
     *
     * @param encodingCode
     * @return
     */
    public WebViewSetter encodingText(String encodingCode) {
        mWebView.getSettings().setDefaultTextEncodingName(encodingCode);
        return this;
    }

    /**
     * 文本编码为 'UTF-8'
     *
     * @return
     */
    public WebViewSetter encodingTextByUTF8() {
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        return this;
    }

    /**
     * 支持硬件加速
     *
     * @param support
     * @return
     */
    public WebViewSetter supportHardwareAccelerated(boolean support) {
        if (!support) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        } else {
            mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        return this;
    }

    /**
     * 显示网络图片
     *
     * @return
     */
    public WebViewSetter showNetworkImage() {
        mWebView.getSettings().setBlockNetworkImage(false);
        return this;
    }

    /**
     * 关闭缓存
     *
     * @return
     */
    public WebViewSetter noCache() {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDatabaseEnabled(false);
        mWebView.getSettings().setAppCacheEnabled(false);
        return this;
    }

    /**
     * 允许文件操作
     *
     * @return
     */
    public WebViewSetter allowFileAccess() {
        mWebView.getSettings().setAllowFileAccess(true);
        return this;
    }

    /**
     * 允许Js开启窗口
     *
     * @return
     */
    public WebViewSetter javaScriptCanOpenWindow() {
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        return this;
    }

    /**
     * 自动加载图片
     *
     * @return
     */
    public WebViewSetter loadImagesAuto() {
        mWebView.getSettings().setLoadsImagesAutomatically(true);
        return this;
    }

    /**
     * 自动加载图片
     *
     * @return
     */
    public WebViewSetter enableDomStorage() {
        mWebView.getSettings().setDomStorageEnabled(true);
        return this;
    }

    /**
     * H5缓存
     *
     * @param cacheDir
     * @return
     */
    public WebViewSetter cacheAppData(String cacheDir) {
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setAppCachePath(cacheDir);
        return this;
    }

    /**
     * 5.0以上WebView允许同时加载Http与Https的混合内容（图片）
     *
     * @return
     */
    public WebViewSetter supportMixContentMode() {
        if (Build.VERSION.SDK_INT >= 21) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        return this;
    }

    /**
     * 回退
     *
     * @return
     */
    public boolean performOnBackPress() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return false;
    }

    /**
     * 导入链接
     *
     * @param url
     */
    public WebViewSetter loadUrl(String url) {
        if (url != null) {
            mWebView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl(url);
                }
            }, 150);
        }
        return this;
    }

    /**
     * 默认的WebViewClient
     *
     * @return
     */
    public WebViewSetter setDefaultWebViewClient() {
        mWebView.setWebViewClient(new WebViewClient() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                if (url != null && (url.startsWith("http") || url.startsWith("https"))) {
                    view.loadUrl(ViewUtils.processUrl(url));
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                if (error.getPrimaryError() == SslError.SSL_INVALID) {
                    handler.proceed();
                } else {
                    handler.cancel();
                }
            }
        });
        return this;
    }

    /**
     * 默认的WebViewClient
     *
     * @return
     */
    public WebViewSetter setDefaultWebChormeClient() {
        mWebView.setWebChromeClient(new WebChromeClient());
        return this;
    }

    /**
     * WebView销毁
     */
    public void destroyWebView() {
        if (mWebView != null) {
            ViewGroup parent = (ViewGroup) mWebView.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
            mWebView.stopLoading();
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearFormData();
            mWebView.clearCache(true);
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }

}
